<?php
namespace Addons\Redguest\Controller\H5;

use Lib\Response;
use Addons\CustomerPortrait\Helper;
use Models\BaseModel as Model;
use Addons\QyWechat\Services\QyWechatApi;
use Addons\QyWechat\Services\JsSdk;

use Addons\QyWechat\Services\WxpayService;

use Addons\Redguest\Helper as QyHelper;
use Addons\QyWechat\Helper as QyHelpers;
class Replys extends \BaseController
{
    public function envelopes(){
        $id = \Request::get('list_id');
        $corp_id = \Request::get('corp_id');
        $agent_id = \Request::get('agent_id');
        $list = (new Model('qy_redguest_list'))->find($id);
        if(!$list->id){
            die('活动不存在'); 
        }

        $redguest = (new \Model('qy_redguest'))->find($list->pid);
        //开启区域限制
        if($redguest->red_area == 3){
            $config = (new Model('qy_fission_config'))->find(['wid'=>$list->wid]);
            $this->assign("list", $list);
            $this->assign("redguest", $redguest);
            $this->assign("config", $config);
            $this->assign("corp_id", $corp_id);
            $this->assign("agent_id", $agent_id);

            return $this->show();
        }
        \Redirect::to('envelope.html?list_id='.$id.'&corp_id='.$corp_id.'&agent_id='.$agent_id);
    }

    public function envelope(){
        $list_id = \Request::get('list_id');
        $corp_id = \Request::get('corp_id');
        $agent_id = \Request::get('agent_id');
        $list = (new Model("qy_redguest_list"))->find(['id'=>$list_id]);
        $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$corp_id]);
        $wid = $qyConfig->wid;
        $cover  = (new Model("qy_red_cover"))->find(["wid"=>$wid]);
        // $replyConfig = (new Model('qy_reply_config'))->find(['wid'=>$wid,'agent_id'=>$agent_id]);
        $replyConfig = QyHelpers::getInstance()->get_message_send_config($wid,$agent_id);
        if($_GET["code"]){
            $code = $_GET['code'];
            $app = QyWechatApi::getInstance()->get_qy_agent_app($corp_id,$replyConfig->agent_id,$replyConfig->secret);
            $accessToken = $app->access_token;
            $token = $accessToken->getToken()['access_token']; // token 数组  token['access_token'] 字符串
            $url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$token.'&code='.$code;
            $resArr = json_decode(curlGet($url),1);
            $user_id = $resArr['external_userid'];
            $OpenId = $resArr['OpenId'];
            $copyright = QyHelpers::copyright($wid);
        }else{
            $redirect_uri = urlencode(Helper::getInstance()->get_http_server_name().'/Addons/Redguest/H5/Replys/envelope.html?corp_id='.$corp_id.'&agent_id='.$replyConfig->agent_id.'&list_id='.$list_id);
            $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$corp_id.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
            \Redirect::to($url);
        }
        $this->assign('cover',$cover);
        $this->assign('corp_id',$corp_id);
        $this->assign('copyright',$copyright);
        $this->assign('user_id',$user_id);
        $this->assign('agent_id',$replyConfig->agent_id);
        $this->assign('OpenId',$OpenId);
        $this->assign('list',$list);
        return $this->show();
    }



   public function subhb(){
        header('Content-type:text/html; Charset=utf-8');
        setApi(); 
        $list_id = $_POST['list_id']; //红包id
        $user_id = $_POST['user_id']; //用戶id
        $openId = $_POST['OpenId']; //用户的OpenId
        $user = (new Model('qy_externalcontact_list'))->find(["external_userid"=>$user_id]);
        $list = (new Model('qy_redguest_list'))->find($list_id);
        $red = (new Model('qy_redguest'))->find(["id"=>$list->pid]);
        if($red->red_area == 2){
            $arr = explode('-', $red->area);
            $arrs = $this->getCitys($red->wid);
            if($arr[0] != $arrs['province']){
                sendError("地区不同");
            }elseif($arr[1] != $arrs['city']){
                sendError("地区不同");
            }elseif($arr[2] != $arrs['district']){
                sendError("地区不同");
            }
        }
        if($red->red_size < 1){
            sendError("红包已领完");
        }
        if(!$user_id && !$openId){
            sendError('不是企业客户');
        }
        if($list->status == 0){
            sendError('您已领取过该红包了');
        }else{
            $list_add = (new Model('qy_redguest_list'))->find($list_id);
            $status = (new Model('qy_redguest'))->find(["id"=>$list_add->pid]);
            $status->red_size = $status->red_size-1;
            $status->save();
            if($status->red_status == 2){
                $rand = $status->red_price + mt_rand() / mt_getrandmax() * (0.3 - $status->red_price);
                $price = floatval(number_format($rand,2));
            }else{
                $price = $status->red_price;
            }
            $confing = (new Model('qy_envelopes_confing'))->find(["wid"=>$list_add->wid]);
            $appids = (new Model('qy_wechat_config'))->find(["wid"=>$list_add->wid]);
            if(!$confing->id || $confing->status == 2){
                $pubs = (new Model('pubs'))->find($list_add->wid);
                $users = (new Model('user'))->find($pubs->uid);
                if($users->balance < $price){
                    sendError("余额不足，请联系管理员充值");
                }
                $confing = (new Model('qy_envelopes_confing'))->find(["wid"=>$users->agid]);
            }
            $wid = $list_add->wid;
            $mchid = $confing->mchid; 
            // $appid = 'wx184a463ef7a7d355';
            $appid = $appids->corp_id;
            // $appid = $confing->appid; 
            $appKey = $confing->appKey; 
            $apiKey = $confing->apiKey; 
            $wxPay = new WxpayService($mchid, $appid, $appKey, $apiKey, $wid);
            if (!$openId) exit('获取openid失败');
            $length = 20;
            $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
            $len = strlen($str)-1;
            $randstr = '';
            for ($i=0;$i<$length;$i++) {
              $num=mt_rand(0,$len);
              $randstr .= $str[$num];
             }
            $outTradeNo = $randstr.$user->id; //订单号
            $payAmount = $price;  //转账金额，单位:元。转账最小金额为0.3元
            $trueName = $user->name;  //收款人真实姓名
            $result = $wxPay->createJsBizPackage($openId, $payAmount, $outTradeNo, $trueName,$wid);
            if($result == "true"){
                if($confing->type != 1){
                    $record = new Model("user_recharge_record");
                    $record->user_id = $users->id;
                    $record->openid = $users->id;
                    $record->money = $payAmount;
                    $record->recharge_time = time();
                    $record->out_trade_no = $outTradeNo;
                    $record->transaction_id = $outTradeNo;
                    $record->type = 2;
                    $record->status = 2;
                    $record->save();
                    // $users->balance = $users->balance - $payAmount;
                    // $users->save();
                }
                $list_add->ltime = time();
                if($user_id){
                    $list_add->userid = $user->id;
                }else{
                    $list_add->userid = $openId;
                }
                $list_add->status = 0;
                $list_add->price = $price;
                $list_add->save();
                if($list_add->id){
                    sendSuccess('领取成功',$list_add->id);
                }
            }else if($result["err_code"]){
                $err_code = (array)$result["err_code"];
                sendError('领取失败',$wxPay->transfers($err_code[0]));
            }else if($result["return_msg"]){
                $return_msg = (array)$result["return_msg"];
                sendError('领取失败',$return_msg[0]);
            }else{
                sendError('领取失败',$result);
            }
        }
    }



    public function check(){
        $list_id = \Request::get('list_id');//抢完红包后的整条记录
        $list = (new Model('qy_redguest_list'))->find($list_id);
        $user = (new Model('qy_externalcontact_list'))->find(["id"=>$list->userid]);
        $cover  = (new Model("qy_red_cover"))->find(["wid"=>$list->wid]);
        $this->assign("cover",$cover);
        $this->assign("user",$user); 
        $this->assign("list",$list);
        return $this->show();
    }


     public function getClientIP()
    {
        if (isset($_SERVER)) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
                foreach ($arr as $ip) {
                    $ip = trim($ip);
                    if ($ip != 'unknown') {
                        $realip = $ip;
                        break;
                    }
                }
                if (!isset($realip)) {
                    $realip = "0.0.0.0";
                }
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $realip = $_SERVER['HTTP_CLIENT_IP'];
            } else {
                if (isset($_SERVER['REMOTE_ADDR'])) {
                    $realip = $_SERVER['REMOTE_ADDR'];
                } else {
                    $realip = '0.0.0.0';
                }
            }
        } else {
            if (getenv('HTTP_X_FORWARDED_FOR')) {
                $realip = getenv('HTTP_X_FORWARDED_FOR');
            } elseif (getenv('HTTP_CLIENT_IP')) {
                $realip = getenv('HTTP_CLIENT_IP');
            } else {
                $realip = getenv('REMOTE_ADDR');
            }
        }
        preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
        $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
        return $realip;
    }


  public function getCitys($wids)
    {
        $missionArr = (new Model('qy_fission_config'))->find(['wid'=>$wids]);
        $getIp = $this->getClientIP();
        // dump($getIp);die;  
        
        $content = file_get_contents("http://api.map.baidu.com/location/ip?ak={$missionArr->ak}&ip={$getIp}&coor=bd09ll");
        $json = json_decode($content,1);
        
        $xxaddress = file_get_contents("http://api.map.baidu.com/geocoder?location={$json['content']['point']['y']},{$json['content']['point']['x']}&output=json&key={$missionArr->ak}");
        $address_detail = json_decode($xxaddress,1);
        // dump($address_detail);die;
        $return['city'] =$address_detail['result']['addressComponent']['city'];
        $return['province'] =$address_detail['result']['addressComponent']['province'];
        $return['district'] =$address_detail['result']['addressComponent']['district'];
        $return['content']=$address_detail;
        return $return;
    }

}